import requests
from .comment import comment
from .user import user
from .link import link
from .linkCollection import linkCollection
from .hiddencomment import hiddencomment

class client:
    
    def __init__(self):
        self.cookies = None
        self.session = None
        self.timeout = 20.0
        self.baseURL = "http://www.reddit.com"
        self.headers = {'User-Agent' : 'IAMAbot/dev by MacHaggis'}
    
    def login(self, username, password):
        payload = { 'api_type' : 'json', 'passwd' : password, 'rem' : 'False', 'user' : username}
        response = requests.post(self.baseURL + "/api/login", data=payload, timeout=self.timeout, headers=self.headers)
        self.cookies = response.cookies
        self.session = session(response.json()["json"])

    def getLoggedInUser(self):
        response = requests.get(self.baseURL + "/api/me.json", cookies=self.cookies, timeout=self.timeout, headers=self.headers)
        return user(response.json()) 

    def getSubReddit(self, name, after=None, limit=25):
        collection = None
        count = limit
        if limit > 100:
            limit = 100
        while count > 0:
            response = requests.get(self.baseURL + "/r/{0}.json?limit={1}&after={2}".format(name, limit, after), cookies=self.cookies, timeout=self.timeout, headers=self.headers)
            if collection is None:
                collection = linkCollection(response.json())
            else:
                newcollection = linkCollection(response.json())
                collection.data += newcollection.data
                collection.after = newcollection.after
                after = newcollection.after
                count = count - limit
                if count < limit:
                    limit = count
        return collection
        
    def getThread(self, url):
        if not url.startswith('http'):
            url = self.baseURL + url
        if url.endswith('/'):
            url = url[0:len(url) - 1]
        if not url.endswith('.json'):
            url = url + '.json'
        response = requests.get(url, cookies=self.cookies, timeout=self.timeout, headers=self.headers)
        return link(response.json()[0]["data"]["children"][0])
    
    def getComments(self, link, parentcommentid=None):
        link  = link.lower()
        if not link.startswith('http'):
            link = self.baseURL + link
        if link.endswith('/'):
            link = link[0:len(link) - 1]
        if parentcommentid is not None:
            if parentcommentid[2] == '_':
                parentcommentid = parentcommentid[3:]
            link = link + "/" + parentcommentid
        if not link.endswith('.json'):
            link = link + '.json'
        response = requests.get(link, cookies=self.cookies, timeout=self.timeout, headers=self.headers)
        for item in response.json()[1]["data"]["children"]:
            if item["kind"] == "Listing" or item["kind"] == "t1":
                yield comment(item)
    
    def getMoreComments(self, linkid, idlist):
        payload = { 'api_type' : 'json', 'link_id' : linkid, 'children' : ",".join(idlist) }
        response = requests.post(self.baseURL + "/api/morechildren/", data=payload, timeout=self.timeout, cookies=self.cookies, headers=self.headers)
        json = response.json()["json"]
        if "data" in json:
            for item in json["data"]["things"]:
                yield hiddencomment(item)
    def postComment(self, fullname, content):
        payload = { 'api_type' : 'json', 'thing_id' : fullname, 'text' : content, 'uh' : self.session.modhash }
        response = requests.post(self.baseURL + "/api/comment", data=payload, timeout=self.timeout, cookies=self.cookies, headers=self.headers)
        try:
            json = response.json()
        except:
            print("No active user. Please log in first.")
        print("reply submitted")
            
        
class session:
    def __init__(self, json):
        self.modhash = json["data"]["modhash"]
        self.cookie = json["data"]["cookie"]
        self.errors = json["errors"]
